package com.jomoo.css.common.core.context;

import cn.hutool.core.util.StrUtil;
import com.jomoo.css.common.core.constant.CommonConstants;
import com.jomoo.css.common.core.util.AssertHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ling
 * @date 2018/9/13
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DefaultContextHolderFilter extends GenericFilterBean {

    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("process request:" + request.getRequestURI());
        String tenantId = request.getHeader(CommonConstants.TENANT_ID);
        log.debug("获取header中的租户ID为:{}", tenantId);
//		System.out.println("获取header中的租户ID为:{}"+tenantId);
//		Enumeration<String> headerNames = request.getHeaderNames();
//		while (headerNames.hasMoreElements()) {
//			String key = (String) headerNames.nextElement();
//			// 排除Cookie字段
//			if (key.equalsIgnoreCase("Cookie")) {
//				continue;
//			}
//			String value = request.getHeader(key);
//			System.out.println("key:"+key+" value:"+value);
//		}
        if (StrUtil.isNotBlank(tenantId)) {
            ContextHolder.setTenantId(tenantId);
        } else {
//			ContextHolder.setTenantId(CommonConstants.TENANT_ID_1);
            /**
             * for activity
             */
            tenantId = request.getHeader("tenantId");
            if (AssertHelper.empty(tenantId)) {
                tenantId = request.getHeader("TENANT_ID");
            }
            if (AssertHelper.empty(tenantId)) {
                tenantId = request.getHeader(CommonConstants.TENANT_ID.toLowerCase());
            }
            ContextHolder.setTenantId(tenantId);
        }

        ContextHolder.setHttpRequestResponseHolder(request, response);
        //每次请求给予一个id,跨服务调用时,这个id会传递
        String sid = ((HttpServletRequest) servletRequest).getHeader(CommonConstants.REQUEST_GROUP_ID);
        String remoteIp = ((HttpServletRequest) servletRequest).getHeader(CommonConstants.REQUEST_REMOTE_IP);
        ContextHolder.setSid(sid);
        ContextHolder.setRemoteIp(remoteIp);

        filterChain.doFilter(request, response);
        ContextHolder.clean();
    }
}
